package com.lry.basic.algorithm.graph;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class AdjList {
    private int V;//顶点数
    private int E;//边数
    private LinkedList<Integer>[] adj;//邻接表，链表数组存储

    public AdjList(String filename){
        File file = new File(filename);
        try(Scanner scanner = new Scanner(file)){
            V = scanner.nextInt();//顶点数
            if(V<=0) throw new RuntimeException("顶点个数必须大于0");
            adj = new LinkedList[V];
            for(int i=0;i<V;i++){
                adj[i] = new LinkedList<>();
            }
            E = scanner.nextInt();//边数
            if(E<0) throw new RuntimeException("边数不能为负数");
            for(int i=0;i<E;i++){
                int a = scanner.nextInt();
                validateVertex(a);
                int b = scanner.nextInt();
                validateVertex(b);
                //自环边检测
                if(a==b){
                    throw new RuntimeException("简单图不能包含自环边");
                }
                //平行边检测
                if(adj[a].contains(b)){
                    throw new RuntimeException("简单图不能包含平行边");
                }
                adj[a].add(b);
                adj[b].add(a);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void validateVertex(int v){
        if(v<0||v>=V){
            throw new RuntimeException("顶点下标溢出");
        }
    }

    public int vertexNum(){
        return V;
    }

    public int edgeNum(){
        return E;
    }

    public boolean hasEdge(int v,int w){
        validateVertex(v);
        validateVertex(w);
        return adj[v].contains(w);
    }

    //邻接顶点
    public List<Integer> adj(int v){
        validateVertex(v);
        return adj[v];
    }

    //度
    public int degree(int v){
        validateVertex(v);
        return adj[v].size();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("V = %d,E = %d\n",V,E));
        for(int i=0;i<adj.length;i++){
            sb.append(i+":");
            for (Iterator<Integer> it = adj[i].iterator(); it.hasNext(); ) {
                sb.append(it.next()+" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        AdjList adjList = new AdjList("graph.txt");
        System.out.println(adjList);
        System.out.println(adjList.degree(6));
    }
}

